package com.mbt.deal.ui.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.android.arouter.launcher.ARouter;
import com.mbt.deal.R;
import com.mbt.deal.api.Api;
import com.mbt.deal.api.ApiServer;
import com.mbt.deal.api.RxBus;
import com.mbt.deal.api.RxResultHelper;
import com.mbt.deal.api.RxSchedulers;
import com.mbt.deal.api.RxSubscriber;
import com.mbt.deal.bean.BaseDataBean;
import com.mbt.deal.bean.BaseListBean;
import com.mbt.deal.bean.CoinListBean;
import com.mbt.deal.bean.CoinPriceBean;
import com.mbt.deal.bean.MessageBean;
import com.mbt.deal.bean.OrderBean;
import com.mbt.deal.bean.UserInfoBean;
import com.mbt.deal.ui.activity.MessageActivity;
import com.mbt.deal.ui.activity.OrderListActivity;
import com.mbt.deal.ui.activity.OrderSaleorBuyActivity;
import com.mbt.deal.ui.activity.TansActionRecordActivity;
import com.mbt.deal.ui.adapter.JiaoYiAdapter;
import com.mbt.deal.ui.contract.DealMainContract;
import com.mbt.deal.ui.model.DealMainModel;
import com.mbt.deal.ui.presenter.DealMainPresenter;
import com.mbt.deal.ui.widgets.CoinTypePop;
import com.mbt.deal.ui.widgets.TubiaoView;
import com.mbt.deal.util.ImageLoadUtil;
import com.mbt.deal.util.MyUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lecho.lib.hellocharts.model.LineChartData;
import rx.functions.Action1;

import static android.content.Context.MODE_PRIVATE;

/**
 * @author Administrator
 * @createtime：2018/8/15 22:57
 */
public class DealbuinessFragment2 extends BaseFragment<DealMainPresenter, DealMainModel> implements DealMainContract.View {
    private ListView mListview;
    private View heardview;
    private View footView;
    private View headrView2;
    private ImageView iv_headportrait;
    private TextView tv_des;
    private TextView tv_name;
    private TextView cash_money;
    private TextView apay_money;
    private RadioButton rb_money_buy;
    private RadioButton rb_money_sale;
    private RadioGroup radioGroup;
    private ProgressBar foot_progress;
    private TextView tv_foot_des;
    private RadioButton rb_money_buy_top;
    private RadioButton rb_money_sale_top;
    private RadioGroup radioGroup_top;
    private LinearLayout ll_top;
    private SwipeRefreshLayout swipeLayout;
    private View ll_sale_order;
    private View ll_buy_order;
    private View ll_order_list;
    private View ll_transaction_record;
    private TextView tv_coin_name;
    private TextView txt_recharge;
    private LinearLayout ll_coinType;
    private ViewFlipper view_flipper;
    private TextView tv_title;
    private TubiaoView tubiaoView;
    private int pageNum = 1;
    private int pageSzie = 10;
    private int orderType = 1;//1求购  2 出售
    private int totalCount;
    private JiaoYiAdapter jiaoYiAdapter;
    private boolean canLoadMore = true;
    private boolean isLoadingMore = false;
    private boolean isloadingData = false;

    private LineChartData data;
    private int maxNumberOfLines = 4;
    private int numberOfPoints = 20;
    private String coinName;
    private String coinId;

    private SharedPreferences sp;
    public static final String DEALBUINESSFRAGMENTRXBUS = "DEALBUINESSFRAGMENTRXBUS";
    public static final String SWIPEREFRESH_ON = "SWIPEREFRESH_ON";
    public static final String SWIPEREFRESH_OFF = "SWIPEREFRESH_OFF";

    String userDesc;//用户描述

    String nowPrice;//当前价格

    String coinCount;//币种个数

    List<CoinListBean> coinListBeans = new ArrayList<>();
    private CoinTypePop typePop;
    private List<MessageBean> messageBeanList;

    @Override
    protected int getLayoutResource() {
        return R.layout.deal_buiness_fragment_second;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
        refreshPage();
    }

    @Override
    protected void initView(View view) {

        sp = mContext.getSharedPreferences("config", MODE_PRIVATE);
        mListview = view.findViewById(R.id.listview);
        ll_coinType = view.findViewById(R.id.ll_coinType);
        tv_title = view.findViewById(R.id.tv_title);
        swipeLayout = view.findViewById(R.id.swipeLayout);
        swipeLayout.setColorSchemeResources(R.color.common_bg, R.color.common_bg, R.color.common_bg);
        rb_money_buy_top = view.findViewById(R.id.rb_money_buy_top);
        rb_money_sale_top = view.findViewById(R.id.rb_money_sale_top);
        radioGroup_top = view.findViewById(R.id.radioGroup_top);
        ll_top = view.findViewById(R.id.ll_top);
        rb_money_buy_top.setChecked(true);
        heardview = LayoutInflater.from(mContext).inflate(R.layout.heard_view, null);
        footView = LayoutInflater.from(mContext).inflate(R.layout.foot_view, null);
        headrView2 = LayoutInflater.from(mContext).inflate(R.layout.type_layout, null);
        view_flipper = heardview.findViewById(R.id.view_flipper);
        tv_coin_name = heardview.findViewById(R.id.tv_coin_name);
        tubiaoView = heardview.findViewById(R.id.tubiao_view);
        cash_money = heardview.findViewById(R.id.cash_money);
        apay_money = heardview.findViewById(R.id.apay_money);
        rb_money_buy = headrView2.findViewById(R.id.rb_money_buy);
        rb_money_sale = headrView2.findViewById(R.id.rb_money_sale);
        radioGroup = headrView2.findViewById(R.id.radioGroup);
        iv_headportrait = heardview.findViewById(R.id.iv_headportrait);
        tv_des = heardview.findViewById(R.id.tv_des);
        tv_name = heardview.findViewById(R.id.tv_name);
        foot_progress = footView.findViewById(R.id.progress);
        tv_foot_des = footView.findViewById(R.id.tv_foot_des);
        ll_sale_order = heardview.findViewById(R.id.ll_sale_order);
        ll_sale_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), OrderSaleorBuyActivity.class);
                intent.putExtra("orderType", 2);
                intent.putExtra("userDesc", userDesc);
                intent.putExtra("nowPrice", nowPrice);
                intent.putExtra("coinCount", coinCount);
                intent.putExtra("coinName", coinName);
                intent.putExtra("coinId", coinId);
                intent.putExtra("cashmoney", cash_money.getText().toString().trim());
                Bundle bundle = new Bundle();
                bundle.putSerializable("messageBeanList", (Serializable) messageBeanList);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        ll_buy_order = heardview.findViewById(R.id.ll_buy_order);
        ll_buy_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), OrderSaleorBuyActivity.class);
                intent.putExtra("orderType", 1);
                intent.putExtra("userDesc", userDesc);
                intent.putExtra("nowPrice", nowPrice);
                intent.putExtra("coinCount", coinCount);
                intent.putExtra("coinName", coinName);
                intent.putExtra("coinId", coinId);
                intent.putExtra("cashmoney", cash_money.getText().toString().trim());
                Bundle bundle = new Bundle();
                bundle.putSerializable("messageBeanList", (Serializable) messageBeanList);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        ll_order_list = heardview.findViewById(R.id.ll_order_list);
        ll_order_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), OrderListActivity.class));
            }
        });

        ll_transaction_record = heardview.findViewById(R.id.ll_transaction_record);
        ll_transaction_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), TansActionRecordActivity.class));
            }
        });

        txt_recharge = view.findViewById(R.id.txt_recharge);
        txt_recharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/personal/RechargeActivity")
                        .navigation();
            }
        });
        mListview.addHeaderView(heardview);
        mListview.addHeaderView(headrView2);
        mListview.addFooterView(footView);
        jiaoYiAdapter = new JiaoYiAdapter(mContext, orderType);
        mListview.setAdapter(jiaoYiAdapter);
        rb_money_buy.setChecked(true);
        radioGroup.setOnCheckedChangeListener(checkedChangeListener);

        setListviwScroll();
        setCbCheck();
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshPage();
            }
        });
        ll_coinType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTypePop();
            }
        });

        RxBus.getInstance().register(DEALBUINESSFRAGMENTRXBUS).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                refreshPage();
            }
        });

        RxBus.getInstance().register(SWIPEREFRESH_ON).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                swipeLayout.setEnabled(true);
            }
        });
        RxBus.getInstance().register(SWIPEREFRESH_OFF).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                swipeLayout.setEnabled(false);
            }
        });
    }

    private void showTypePop() {
        if (typePop == null) {
            typePop = new CoinTypePop(mContext);
            typePop.setData(coinListBeans);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            typePop.showAsDropDown(ll_coinType, 0, 10, Gravity.CENTER_HORIZONTAL);
        } else {
            typePop.showAsDropDown(ll_coinType);
        }
        typePop.getmListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                coinName = coinListBeans.get(position).getName();
                coinId = coinListBeans.get(position).getId() + "";
                tv_coin_name.setText(coinName);
                tv_title.setText(coinName);
                refreshPage();
                typePop.dismiss();
            }
        });
    }

    private RadioGroup.OnCheckedChangeListener checkedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.rb_money_buy) {
                orderType = 1;
                rb_money_buy_top.setChecked(true);

            } else if (checkedId == R.id.rb_money_sale) {
                orderType = 2;
                rb_money_sale_top.setChecked(true);
            } else if (checkedId == R.id.rb_money_buy_top) {
                orderType = 1;
                rb_money_buy.setChecked(true);
            } else if (checkedId == R.id.rb_money_sale_top) {
                orderType = 2;
                rb_money_sale.setChecked(true);
            }
            pageNum = 1;
            isloadingData = true;
            canLoadMore = true;
            mPresenter.getOrderList(orderType, pageNum, pageSzie);
            foot_progress.setVisibility(View.VISIBLE);
            tv_foot_des.setText("加载更多");
        }
    };

    private void setCbCheck() {

    }

    private void setListviwScroll() {
        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount == totalItemCount && canLoadMore && !isLoadingMore && !isloadingData) {
                    pageNum++;
                    isLoadingMore = true;
                    mPresenter.getOrderList(orderType, pageNum, pageSzie);
                }
                if (firstVisibleItem < 1) {
                    if (ll_top.getVisibility() == View.VISIBLE) {
                        ll_top.setVisibility(View.GONE);
                        radioGroup_top.setOnCheckedChangeListener(null);
                        radioGroup.setOnCheckedChangeListener(checkedChangeListener);
                    }
                } else {
                    if (ll_top.getVisibility() == View.GONE) {
                        ll_top.setVisibility(View.VISIBLE);
                        radioGroup_top.setOnCheckedChangeListener(checkedChangeListener);
                        radioGroup.setOnCheckedChangeListener(null);
                    }
                }
            }
        });
    }


    @Override
    public void showPric(CoinPriceBean bean) {
        nowPrice = bean.getPricenow();
        swipeLayout.setRefreshing(false);
        tubiaoView.setPrice(bean.getPricelow(), bean.getPricenow(), bean.getPricehigh());
    }

    @Override
    public void showCoinCount(String count) {
        coinCount = count;
        apay_money.setText(count);
    }

    @Override
    public void showcurrency(List<CoinListBean> ls) {
        this.coinListBeans = ls;
        swipeLayout.setRefreshing(false);
        coinName = ls.get(0).getName();
        coinId = ls.get(0).getId() + "";
        tv_coin_name.setText(coinName);
        tv_title.setText(coinName);
        tubiaoView.setCoinid(coinId);
    }

    @Override
    public void showOrderBean(List<OrderBean> list, int totalcount) {
        this.totalCount = totalcount;
        isLoadingMore = false;
        isloadingData = false;
        swipeLayout.setRefreshing(false);
        if (pageNum == 1) {
            jiaoYiAdapter.setLists(list, orderType);
        } else {
            jiaoYiAdapter.addLists(list);
        }

        if (jiaoYiAdapter.getCount() == this.totalCount) {
            canLoadMore = false;
            foot_progress.setVisibility(View.GONE);
            tv_foot_des.setText("已经加载全部数据");
        }
    }


    private void refreshPage() {
        pageNum = 1;
        isloadingData = true;
        mPresenter.getOrderList(orderType, pageNum, pageSzie);
        getuserInfo();
        getMessages();
        if (TextUtils.isEmpty(coinId)) {
            mPresenter.getCoinList();
        }
        if (!TextUtils.isEmpty(coinId)) {
            mPresenter.getCoinCount(coinId);
            mPresenter.getConinPrice(coinId);
            tubiaoView.setCoinid(coinId);
        }

    }

    private void getuserInfo() {
        Api.getServer(ApiServer.class).getuserinfo(MyUtils.getToken(mContext), new HashMap<String, Object>()).compose(RxSchedulers.<BaseDataBean<UserInfoBean>>io_main())
                .compose(RxResultHelper.<BaseDataBean<UserInfoBean>>handleResult()).subscribe(new RxSubscriber<BaseDataBean<UserInfoBean>>(mContext) {

            @Override
            public void _onNext(BaseDataBean<UserInfoBean> userInfoBeanBaseDataBean) {
                String heardPhotoUrl = userInfoBeanBaseDataBean.data.getHeadimage();
                String niceName = userInfoBeanBaseDataBean.data.getName();
                String userMoney = userInfoBeanBaseDataBean.data.getUsablemoney();
                cash_money.setText(MyUtils.formatDouble(Double.parseDouble(userMoney)));
                userDesc = userInfoBeanBaseDataBean.data.getRemark();
                tv_des.setText(userInfoBeanBaseDataBean.data.getRemark());
                tv_name.setText(niceName);
                ImageLoadUtil.loadImage(heardPhotoUrl, iv_headportrait);
            }

            @Override
            public void _onError(String message) {

            }

            @Override
            public void onCompleted() {

            }
        });
    }

    private void getMessages() {
        Api.getServer(ApiServer.class).getmessages(MyUtils.getToken(mContext), new HashMap<String, Object>()).compose(RxResultHelper.<BaseListBean<MessageBean>>handleResult())
                .compose(RxSchedulers.<BaseListBean<MessageBean>>io_main()).subscribe(new RxSubscriber<BaseListBean<MessageBean>>(mContext) {
            @Override
            public void _onNext(BaseListBean<MessageBean> stringBaseListBean) {
                messageBeanList = stringBaseListBean.data;
                view_flipper.removeAllViews();
                for (int i = 0; i < stringBaseListBean.count; i++) {
                    TextView textView = new TextView(mContext);
                    textView.setTextColor(Color.parseColor("#ffffff"));
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15f);
                    textView.setSingleLine(true);
                    textView.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    textView.setText(stringBaseListBean.data.get(i).getTitle());
                    view_flipper.addView(textView);
                }

                view_flipper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, MessageActivity.class);
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void _onError(String message) {

            }

            @Override
            public void onCompleted() {

            }
        });
    }


}
